import string
import random

import django.contrib.auth
from django.contrib.auth import get_user_model,login,logout
from django.urls import reverse

User = get_user_model()
from django.core.mail import send_mail
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.views.decorators.http import require_http_methods

from sshauth.models import CaptchaModel
from sshauth.form import RegisterForm,LoginForm


# Create your views here.

@require_http_methods(['GET', 'POST'])
def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            remember = form.cleaned_data.get('remember')
            user = User.objects.filter(username=username).first()
            if user and user.check_password(password):
                django.contrib.auth.login(request,user)
                if remember:
                    request.session.set_expiry(60 * 60 * 24 * 30)
                else:
                    request.session.set_expiry(0)
                return redirect(reverse('blog:index'))
            else:
                form.add_error('username', '用户名或密码错误')
                print(form.errors)
                return render(request, 'login.html', {'form': form})


@require_http_methods(['GET', 'POST'])
def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    else:
        form = RegisterForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            password = form.cleaned_data.get('password')
            username = form.cleaned_data.get('username')
            User.objects.create_user(email=email, password=password, username=username)
            return redirect(reverse('sshauth:login'))
        else:
            print(form.errors)
            # return redirect(reverse('sshauth:register'))
            return render(request, 'register.html', {'form': form})

def logout_view(request):
    logout(request)
    return redirect(reverse('sshauth:login'))

def sendEmail(request):
    email = request.GET.get('email')
    if not email:
        return JsonResponse({'code': 400, 'msg': '请输入正确的邮箱'})
    #  生成验证码
    code = ''.join(random.sample(string.ascii_letters + string.digits, 4))
    CaptchaModel.objects.update_or_create(email=email, defaults={'captcha': code})
    send_mail(subject='注册验证码', message=f"您的验证码为：{code}", from_email=None, recipient_list=[email])
    return JsonResponse({'code': 200, 'msg': '发送成功'})